<template>
  <div class="upload-avatar">
    <div class="upload-content" @click="dialogVisible = true">
      <img
        :src="
          userInfo.avatar
            ? userInfo.imgHost + userInfo.avatar
            : require('@/static/UserAvatar.png')
        "
        alt=""
      />
      <i class="iconfont icon-xiangji"></i>
    </div>
    <h1>{{ userInfo.nickname }}</h1>
    <span>这个人很懒，什么都没有留下～</span>
    <el-dialog
      title="选择图片"
      :visible.sync="dialogVisible"
      :modal-append-to-body="false"
      :close-on-click-modal="false"
    >
      <div class="upload-dialog-item" v-if="!isShowCropper">
        <i class="iconfont icon-xiangji"></i>
        <p>请选择头像图片</p>
        <el-button type="primary" @click="handleOpenFile">选择图片</el-button>
        <input
          ref="uploadFile"
          type="file"
          name=""
          id=""
          accept="image/*"
          v-show="false"
          @change="handleChangeFile"
        />
      </div>
      <div class="cropper-content" v-else>
        <div class="cropper-box">
          <div class="cropper">
            <vue-cropper
              ref="cropper"
              :img="option.img"
              :outputSize="option.outputSize"
              :outputType="option.outputType"
              :info="option.info"
              :canScale="option.canScale"
              :autoCrop="option.autoCrop"
              :autoCropWidth="option.autoCropWidth"
              :autoCropHeight="option.autoCropHeight"
              :fixed="option.fixed"
              :fixedNumber="option.fixedNumber"
              :full="option.full"
              :fixedBox="option.fixedBox"
              :canMove="option.canMove"
              :canMoveBox="option.canMoveBox"
              :original="option.original"
              :centerBox="option.centerBox"
              :height="option.height"
              :infoTrue="option.infoTrue"
              :maxImgSize="option.maxImgSize"
              :enlarge="option.enlarge"
              :mode="option.mode"
            >
            </vue-cropper>
          </div>
        </div>
        <div class="close-cropper" @click="isShowCropper = false">
          <i class="el-icon-close"></i>
        </div>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="handleSubmit">应用</el-button>
        <el-button @click="handleClose">取消</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
// import { VueCropper } from "vue-cropper";
// import { uploadAvatar } from "@/api/api";
import { mapState, mapMutations } from "vuex";
export default {
  name: "",
  // components: { VueCropper },
  data() {
    return {
      dialogVisible: false,
      isShowCropper: false,
      option: {
        img: "", //裁剪图片的地址
        outputSize: 1, //裁剪生成图片的质量(可选0.1 - 1)
        outputType: "jpeg", //裁剪生成图片的格式（jpeg || png || webp）
        info: true, //图片大小信息
        canScale: true, //图片是否允许滚轮缩放
        autoCrop: true, //是否默认生成截图框
        autoCropWidth: 300, //默认生成截图框宽度
        autoCropHeight: 300, //默认生成截图框高度
        fixed: true, //是否开启截图框宽高固定比例
        fixedNumber: [1, 1], //截图框的宽高比例
        full: false, //false按原比例裁切图片，不失真
        fixedBox: true, //固定截图框大小，不允许改变
        canMove: true, //上传图片是否可以移动
        canMoveBox: true, //截图框能否拖动
        original: false, //上传图片按照原始比例渲染
        centerBox: true, //截图框是否被限制在图片里面
        height: true, //是否按照设备的dpr 输出等比例图片
        infoTrue: false, //true为展示真实输出图片宽高，false展示看到的截图框宽高
        maxImgSize: 3000, //限制图片最大宽度和高度
        enlarge: 1, //图片根据截图框输出比例倍数
        // mode: "230px 150px", //图片默认渲染方式
      },
    };
  },
  computed: {
    ...mapState(["userInfo"]),
  },
  created() {},
  methods: {
    ...mapMutations(["setUserInfo"]),
    handleOpenFile() {
      this.$refs.uploadFile.click();
    },
    handleChangeFile(e) {
      this.isShowCropper = true;
      let file = e.target.files[0];
      if (!/\.(jpg|jpeg|png|JPG|PNG)$/.test(e.target.value)) {
        this.$message({
          message: "图片类型要求：jpeg、jpg、png",
          type: "error",
        });
        return false;
      }
      //转化为blob
      let reader = new FileReader();
      reader.onload = (e) => {
        let data;
        if (typeof e.target.result === "object") {
          data = window.URL.createObjectURL(new Blob([e.target.result]));
        } else {
          data = e.target.result;
        }
        this.option.img = data;
      };
      //转化为base64
      reader.readAsDataURL(file);
    },
    handleSubmit() {
      this.$refs.cropper.getCropBlob(async (data) => {
        // do something
        // console.log(data);
        // console.log(this.$refs.uploadFile.files[0]);
        let files = new File([data], "avatar.jpg");
        let formData = new FormData();
        formData.append("id", this.userInfo.id);
        formData.append("file", files);
        const res = await this.$api.uploadAvatar(formData);
        // console.log(res);
        this.userInfo.avatar = res.data.imgUrl;
        this.setUserInfo({value:this.userInfo,app:this});
        this.dialogVisible = false;
        this.isShowCropper = false;
      });
    },
    handleClose() {
      this.dialogVisible = false;
      this.isShowCropper = false;
    },
  },
};
</script>

<style lang="less" scoped>
.upload-avatar {
  text-align: center;
  width: 200px;
  .upload-content {
    position: relative;
    margin: 0 auto;
    width: 76px;
    height: 76px;
    border-radius: 50%;
    border: 2px solid #fff;
    margin-bottom: 20px;
    overflow: hidden;
    cursor: pointer;
    img {
      width: 100%;
      height: 100%;
    }
    i {
      display: none;
      position: absolute;
      left: 0;
      top: 0;
      width: 100%;
      height: 100%;
      font-size: 30px;
      color: #fff;
      justify-content: center;
      align-items: center;
      background: rgba(0, 0, 0, 0.3);
    }
    &:hover {
      i {
        display: flex;
      }
    }
  }
  h1 {
    font-size: 24px;
    margin-bottom: 10px;
    word-wrap: break-word;
  }
  span {
    display: block;
    font-size: 14px;
    margin-bottom: 20px;
    color: #999;
  }
  /deep/.el-dialog {
    width: initial;
    max-width: 600px;
    text-align: initial;
    .el-dialog__body {
      padding: 0;
      .upload-dialog-item {
        display: flex;
        flex-direction: column;
        align-items: center;
        padding: 30px 20px;
        i {
          font-size: 50px;
        }
        p {
          font-size: 16px;
          margin: 5px auto 20px;
        }
      }
      .cropper-content {
        position: relative;
        display: flex;
        display: -webkit-flex;
        justify-content: flex-end;
        .cropper-box {
          flex: 1;
          width: 100%;
          .cropper {
            width: auto;
            height: 300px;
          }
        }
        .close-cropper {
          position: absolute;
          top: 5px;
          right: 5px;
          width: 24px;
          display: flex;
          justify-content: center;
          align-items: center;
          height: 24px;
          font-size: 16px;
          border-radius: 50%;
          color: #fff;
          background: rgba(0, 0, 0, 0.3);
          cursor: pointer;
        }
      }
    }
  }
}
</style>